package com.example.dormmanage.service.impl;

import com.example.dormmanage.dao.IAdminDao;
import com.example.dormmanage.dao.IStudentDao;
import com.example.dormmanage.entity.Admin;
import com.example.dormmanage.entity.Student;
import com.example.dormmanage.view.ResultView;
import com.example.dormmanage.view.UserVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;

@Service
public class UserService {
    @Autowired
    private IStudentDao studentDao;

    @Autowired
    private IAdminDao adminDao;

    //修改密码
    @Transactional(rollbackFor = Exception.class)
    public ResultView<String> updatePassword(UserVo vo) {
        //获取SecurityContexHolder中的用户id
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        //修改宿舍管理员的密码
        Admin admin = loginUser.getAdmin();
        Student student = loginUser.getStudent();
        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        if(admin != null && student == null){
            admin.setPassword(passwordEncoder.encode(vo.getPassword()));
            admin.setUpdateTime(LocalDateTime.now());
            adminDao.updateById(admin);
        }
        //修改学生的密码
        if(student != null && admin == null){
            student.setPassword(passwordEncoder.encode(vo.getPassword()));
            student.setUpdateTime(LocalDateTime.now());
            studentDao.updateById(student);
        }
        return ResultView.success("修改成功");
    }
}
